<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{padding: 0;margin:0;}
        .box{
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: rgb(255,0,0);
        }
    </style>
</head>
<body>
    <div class="box"><button id="back">原路返回</button></div>

    <script>
        var box = document.getElementsByClassName('box')[0];
        var arr = [];
        var back = document.getElementById('back');
        // box.onclick = function(e){
        //     console.log(e)
        // }
        box.onmousedown = function(e){
            var x = e.offsetX;
            var y = e.offsetY;
            arr.push({
                x:0,
                y:0
            })
            box.onmousemove = function(e){
                box.style.left = e.clientX - x + 'px';
                box.style.top = e.clientY - y + 'px';
                arr.push({
                    x: e.clientX - x,
                    y: e.clientY - y
                })
            }
        }
        box.onmouseup = function(){
            box.onmousemove = null;
        }
        // back.onclick = function(){
            // var len = arr.length - 1;
            // var id = setInterval(function(){                
            //     box.style.left = arr[len].x + 'px';
            //     box.style.top = arr[len].y + 'px';
            //     len--;
            //     if(len < 0 ){
            //         clearInterval(id)
            //         arr = [] //防止每次返回 所有轨迹都返回一遍 
            //     }
            // },20)
        
        back.onmousedown = function(e){
            e.stopPropagation();  //点击back时会冒泡到上一级 故要在back.onmousedown中阻止冒泡才能阻止再在arr中加入（0，0）
        }
        
        back.onclick = function(){
            var id = setInterval(function(){   
                var pos = arr.pop(); //返回最后一个对象             
                box.style.left = pos.x + 'px';
                box.style.top = pos.y + 'px';
                if(arr.length == 0 ){
                    clearInterval(id)
                }
            },30)
        }    

        // document.body.onclick = function(e){
        //     console.log('body')
        //     // e.stopPropagation();
        // }
        // box.onclick = function(e){
        //     console.log('box')
        //     // e.stopPropagation();
        // }
        // back.onclick = function(e){
        //     console.log('back')
        //     // e.stopPropagation();  //阻止上级的onclick事件发生 冒泡
        // }

    </script>
</body>
</html>